package com.kevin.utility.db;

import com.kevin.utility.enums.Separator;

/**
 * @author Random.Lj
 * 切换动态数据源
 *
 */
public class DbContextHolder {
	
	@SuppressWarnings("rawtypes")
	private static final ThreadLocal CONTEXT_HOLDER = new ThreadLocal();
	
	public static final String MASTER = "dataSource_master";
	
	public static void selectDataSource(String driverName, String url, String username, String password) {
		setDbType(driverName + Separator.AND.getText() + url + Separator.AND.getText() + username + Separator.AND.getText() + password);
	}
	
	public static void endSelectDataSource() {
		clearDbType();
	}
	
	@SuppressWarnings("unchecked")
	private static void setDbType(String dbType) {
		CONTEXT_HOLDER.set(dbType);
	}
	
	public static String getDbType() {
		String val = (String)CONTEXT_HOLDER.get();
		if (val == null) {
			return MASTER;
		}
		return val;
	}
	
	private static void clearDbType() {
		CONTEXT_HOLDER.remove();
	}
}
